﻿// owner 蒋家伟

#include "WeakReferenceUnitTest.h"

// std
#include <iostream>

// jsdk
#include "UnitTestDataDefine.h"
#include "UnitTestDbgWarnDefine.h"
#include "WeakPtr.h"
#include "WeakReference.h"

using namespace jsdk;

namespace jsdk
{
    class A : public WeakReference
    {
    public:
        // 此函数可以保证在debug模式下如果是野指针时崩溃
        void setValue() { *m_pValue = 10; }
        int value() const { return *m_pValue; }
        A() { m_pValue = new int(0); }
        ~A() { delete m_pValue; }
    private:
        int* m_pValue = nullptr;
    };
}

UNIT_TEST_START(jsdk, WeakReferenceUnitTest)
{
    WeakReferenceUnitTest test;
    bool success = test.testUbPoint();
    UNIT_TEST_DBG_WARN_AND_RETURN_FALSE_UNLESS(success, L"野指针未定义行为测试失败", L"蒋家伟", L"2023-11-10");
    return true;
}

bool jsdk::WeakReferenceUnitTest::testUbPoint() const
{
    A* pA = new A;
    WeakPtr<A> wpA = pA;
    if (wpA)
    {
        wpA->setValue();
    }

    WeakPtr<A> wpB = pA;
    if (wpB)
    {
        wpB->setValue();
    }
    // 将A析构
    delete pA;
    UNIT_TEST_DBG_WARN_AND_RETURN_FALSE_UNLESS(wpA == nullptr && wpB == nullptr, UnitTestUtils::combineErrorTestMsg(true, false, L"弱指针A与弱指针B应该无效"), L"蒋家伟", L"2023-10-10");

    return true;
}
